/**
 * 管理员
 * @author yangjian
 */
define(function(require, exports) {

	//加载依赖
	require("ajaxproxy");
	var common = require("common");

	exports.init = function(configs) {

		//初始化AjaxProxy插件
		$('#submit_btn').AjaxProxy({
			dataType : "json",
			successCode : "000", //成功时返回的code
			method : "post",
			formId : "content-add-form",
			formCheckHandler : function(form_id) {
				return common.formCheckHandler(form_id, true);
			},
			callbackDelay : __global.jdialog.timer,
			timeInterval : __global.jdialog.timer,
			callBack : function (data) {   /* 执行ajax之后的回调函数 */
				common.ajaxCallback(data);
			}
		});

		common.bswitctListInit(configs);
		common.bswitchAddInit();

		exports.sort();

	}

	//菜单排序
	exports.sort = function() {
		//往上移动菜单
		$(".arrow-up").on('click', function() {
			var org = $(this).parents('tr'); //源元素
			var dist = null; //目标元素
			var id = org.data("id");
			if ( org.data('pid') > 0 ) { //二级菜单
				if ( org.prev().data('pid') == 0 ) {
					return false;
				}
				dist = org.prev();
				org.insertBefore(dist);

			} else { //一级菜单
				var dist = org.prevAll('[data-pid="0"]').first();
				org.insertBefore(dist);
				var lastNode = org; //当前一级菜单最后一个子节点
				//移动子类二级菜单
				$('[data-pid="'+id+'"]').each(function(index, element) {
					$(element).insertAfter(lastNode);
					lastNode = element;
				});

			}

			exports.exchangeSort(org, dist);

		});

		//往下移动菜单
		$(".arrow-down").on('click', function() {
			var org = $(this).parents('tr'); //源元素
			var dist = null; //目标元素
			var id = org.data("id");

			if ( org.data('pid') > 0 ) { //二级菜单
				if ( org.next().data('pid') == 0 ) {
					return false;
				}
				dist = org.next();
				org.insertAfter(dist);

			} else { //一级菜单
				var dist = org.nextAll('[data-pid="0"]').first();
				var pid = dist.data('id');
				//获取下一个一级菜单的最后的子节点
				var lastNode = $('[data-pid="'+pid+'"]').last();
				org.insertAfter(lastNode);
				lastNode = org;
				//移动子类二级菜单
				$('[data-pid="'+id+'"]').each(function(index, element) {
					$(element).insertAfter(lastNode);
					lastNode = element;
				});

			}
			exports.exchangeSort(org, dist);

		});
	}

	//交换菜单排序
	exports.exchangeSort = function(org, dist) {

		var data = {
			org_id : org.data("id"),
			org_sort : dist.data("sort"),
			dist_id : dist.data("id"),
			dist_sort : org.data("sort")
		}
		//console.log(data);
		$.post('/admin/menu/exchangeSort', data, function(data) {
			if ( data.code != '000' ) {
				JDialog.tip.work({type:"error", content:"移动菜单失败.", timer : 2000});
			}
		}, 'json');

	}

});
